﻿using System.Timers;
using Sustainalytics.Entities;

using System;
using System.Linq;
using Sustainalytics.Insights.Service;
using Sustainalytics.Utils;
using Sustainalytics.Utils.Serilog;

namespace Sustainalytics.Insights.BusinessLogic
{
    public class AutoUnpublish
	{
        private readonly IInsightRepository _repository;
	    private System.Timers.Timer timer;

        public AutoUnpublish(IInsightRepository repository )
	    {
	        this._repository = repository;

            // run first time at start up
            timer_Elapsed(null, null);
	    }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                // get UTC 2 days ago  and use as reference
                var reference = DateTime.UtcNow.Date.AddDays(-2);
                var list = _repository.ReadUnpublishedWithStatusActive(reference);
                var updates = list.Select(x => new Tuple<Guid, InsightState>(x, InsightState.Unpublished)).ToList();
                _repository.Update(updates);
                
            }
            finally
            {
                // place the timer for the next run
                if (timer == null || !timer.Enabled)
                {
                    // reset timer 
                    var now = DateTime.UtcNow;
                    var nextrun = now.Date.AddDays(1) - now;
                    // run  next 00:00

                    timer = new System.Timers.Timer();
                    timer.Interval = nextrun.TotalMilliseconds;
                    timer.Elapsed += timer_Elapsed;
                    timer.AutoReset = false;
                    timer.Start();
                }
            }
        }
	}
}

